﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace MyCleverMissionEditor
{
    class LogWatcher : FileSystemWatcher
    {
        //The name of the file to monitor
        private string logFileName;

        private FileStream stream;
        private StreamReader reader;

        //Constructor for the LogWatcher class
        public LogWatcher(string logFileName)
        {
            this.logFileName = logFileName;
            this.Changed += this.OnChanged;

            //Create the FileStream and StreamReader object for the file
            this.stream = new System.IO.FileStream(this.logFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            this.reader = new System.IO.StreamReader(this.stream);
            
            //Set the position of the stream to the end of the file
            this.stream.Position = this.stream.Length;
        }

        public void OnChanged(object o, FileSystemEventArgs e)
        {
            //Fire the TextChanged event
            LogWatcherEventArgs args = new LogWatcherEventArgs(this.reader.ReadToEnd());
            if (this.TextChanged != null)
            {
                this.TextChanged(this, args);
            }
        }

        public delegate void LogWatcherEventHandler(object sender, LogWatcherEventArgs e);

        //Event that is fired when the file is changed
        public event LogWatcherEventHandler TextChanged;
    }

    public class LogWatcherEventArgs : EventArgs
    {
        private string contents;

        public string Contents
        {
            get { return this.contents; }
        }

        public LogWatcherEventArgs(string contents)
        {
            this.contents = contents;
        }
    }
}
